package com.boot.watermark;



import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.ShapeObject;
import org.apache.commons.lang3.StringUtils;

import java.awt.*;

public class WatermarkWordUtils {

    /**
     * 添加文字水印
     *
     * @param watermark:
     * @param srcPath:
     * @param destPath:
     * @return java.lang.String
     * @Description:
     * @Author: mkq
     * @Date: 2022/4/8 15:44
     **/
    public static String addTextWatermark(TextWatermark11 watermark, String srcPath, String destPath) {
        //加载示例文档
        Document doc = new Document();
        doc.loadFromFile(srcPath);
        if (watermark.getTileMode() == 1) {
            insertTextWatermark(doc.getSections().get(0), watermark);
        } else {
            multiRowWatermark(watermark, doc);
        }
        destPath = StringUtils.isEmpty(destPath) ? destPath : newFileName(destPath);
        //保存文档
        doc.saveToFile(destPath, FileFormat.Docx_2013);
        return destPath;
    }

    /**
     * 加水印的文件路径
     *
     * @param fileName
     * @return destPath
     */
    public static String newFileName(String fileName) {
        String rep = "_yuan" ;
        return fileName.replace(rep, "");
    }

    /**
     * 获取文本内容的宽高
     *
     * @param watermark:
     * @return java.lang.String 宽,高
     * @Description:
     * @Author: mkq
     * @Date: 2022/4/8 14:13
     **/
    public static String getTextWidthHeight(TextWatermark11 watermark) {
        Font f = new Font(watermark.getFontFamily(), Font.BOLD, watermark.getFontSize());
        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(f);
        return fm.stringWidth(watermark.getText()) + "," + fm.getHeight();
    }


    public static void multiRowWatermark(TextWatermark11 watermark, Document doc) {
        String[] textWidthHeight = getTextWidthHeight(watermark).split(",");
        //添加艺术字并设置大小
        ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
        shape.setWidth(Integer.parseInt(textWidthHeight[0]));
        shape.setHeight(Integer.parseInt(textWidthHeight[1]));
        //设置艺术字文本内容、位置、旋转及样式
//        shape.setVerticalPosition(30);
//        shape.setHorizontalPosition(20);
        shape.setRotation(watermark.getRadAngle());
        shape.getWordArt().setFontFamily(watermark.getFontPath());
        shape.getWordArt().setText(watermark.getText());
//        shape.setLineStyle(ShapeLineStyle.Single);
        final String color = watermark.getColor();
//        if (color != null) {
//            final String[] rgbs = color.split(",");
//            shape.setStrokeColor(new Color(Integer.parseInt(rgbs[0].trim()), Integer.parseInt(rgbs[1].trim()), Integer.parseInt(rgbs[2].trim()), watermark.getOpacity()));
//        } else {
            shape.setStrokeColor(new Color(192, 192, 192, 255));
//        }
        shape.setStrokeWeight(1);

        Section section;
        HeaderFooter header;
        for (int n = 0; n < doc.getSections().getCount(); n++) {
            section = doc.getSections().get(n);
            //获取section的页眉
            header = section.getHeadersFooters().getHeader();
            Paragraph paragraph;

            if (header.getParagraphs().getCount() > 0) {
                //如果页眉有段落，取它第一个段落
                paragraph = header.getParagraphs().get(0);
            } else {
                //否则新增加一个段落到页眉
                paragraph = header.addParagraph();
            }
            // 获取页面的高度和宽度
            double height = section.getPageSetup().getPageSize().getHeight();
            double width = section.getPageSetup().getPageSize().getWidth()+200;
            final int pageModeOfHorizontalInterval = watermark.getPageModeOfHorizontalInterval() == null ? (int) shape.getWidth() : watermark.getPageModeOfHorizontalInterval();
            final int pageModeOfVerticalInterval = watermark.getPageModeOfVerticalInterval() == null ? (int) shape.getHeight() : watermark.getPageModeOfVerticalInterval();
//            for (int x = 0; x < 3; x++) {
//                for (int y = 0; y < 4; y++) {
//                    //复制艺术字并设置多行多列位置
//                    shape = (ShapeObject) shape.deepClone();
//                    shape.setVerticalPosition(shape.getHeight() + (shape.getHeight() + pageModeOfVerticalInterval) * x);
//                    shape.setHorizontalPosition(shape.getWidth() + 160 * y);
//                    paragraph.getChildObjects().add(shape);
//                }
//            }
//            for (float posX = 0f; posX < height; posX = posX + shape.getHeight() + pageModeOfVerticalInterval+100) {
//                for (float posY = -320f; posY < width; posY = posY + 200) {
//                    shape = (ShapeObject) shape.deepClone();
//                    shape.setVerticalPosition(posX);
//                    shape.setHorizontalPosition(posY);
//                    paragraph.getChildObjects().add(shape);
//                }
//            }

            for (float posX = 0f; posX < height; posX = posX + shape.getHeight() + pageModeOfVerticalInterval+100) {
                for (float posY = -320f; posY < width; posY = posY + 200) {
                    shape = (ShapeObject) shape.deepClone();
                    shape.setVerticalPosition(posX);
                    shape.setHorizontalPosition(posY);
                    paragraph.getChildObjects().add(shape);
                }
            }
        }


    }

    /**
     * 单行文本
     * 自定义文本水印的属性（字体、字号、字体颜色和排版格式）
     *
     * @param section
     */
    private static void insertTextWatermark(Section section, TextWatermark11 watermark) {
        TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText(watermark.getText());
        txtWatermark.setFontSize(watermark.getFontSize());
        final String color = watermark.getColor();
        if (color != null) {
            final String[] rgbs = color.split(",");
            txtWatermark.setColor(new Color(Integer.parseInt(rgbs[0].trim()), Integer.parseInt(rgbs[1].trim()), Integer.parseInt(rgbs[2].trim())));
        } else {
            txtWatermark.setColor(Color.black);
        }
        txtWatermark.setLayout(WatermarkLayout.Diagonal);
        section.getDocument().setWatermark(txtWatermark);
    }

    public static final String DEST = "C:\\Users\\Administrator\\Desktop\\00101.docx";
    public static final String IMG = "C:\\Users\\Administrator\\Desktop\\xiao.jpeg";
    public static final String SRC = "C:\\Users\\Administrator\\Desktop\\001.docx";
    public static final String FONT = "C:\\temp\\songti.ttf";

    public static void main(String[] args) {

//        final ImageWatermark watermark = new ImageWatermark();
//        watermark.setTileMode(1);
//        watermark.setOpacity(0.5F);
//        watermark.setPath(IMG);
//        addImageWatermark(watermark, SRC, DEST);

        final TextWatermark11 watermark12 = new TextWatermark11();
        watermark12.setTileMode(1);
        watermark12.setOpacity(0.5F);
        watermark12.setText("大中国");
        watermark12.setColor("0,0,0");
        watermark12.setRadAngle(325F);
//        watermark12.setPath(IMG);
        addTextWatermark(watermark12, SRC, DEST);

//        //加载Word文档
//        Document doc = new Document();
//        doc.loadFromFile(SRC);
//
//        //创建TextWatermark实例
//        TextWatermark textWatermark = new TextWatermark();
//
//        //设置水印文本内容
//        textWatermark.setText("内部使用");
//
//        //自定义文本水印的属性（字体、字号、字体颜色和排版格式）
//        textWatermark.setFontName("宋体");
//        textWatermark.setFontSize(60);
//        textWatermark.setColor(Color.RED);
//        textWatermark.setLayout(WatermarkLayout.Diagonal);
//
//        //将文本水印添加到文档
//        doc.setWatermark(textWatermark);
//
//        //保存结果文件
//        doc.saveToFile("文本水印.docx", FileFormat.Docx_2013);
    }

    public static String addImageWatermark(ImageWatermark imageWatermark, String srcPath, String destPath) {

        if (imageWatermark.getTileMode() == 1) {
            destPath = imageRowWatermark(imageWatermark, srcPath, destPath);
        } else {
            destPath = imgWatermark(imageWatermark, srcPath, destPath);
        }
        return destPath;
    }

    public static String imageRowWatermark(ImageWatermark imageWatermark, String srcPath, String destPath) {
        //加载示例文档
        Document doc = new Document();
        doc.loadFromFile(srcPath);
        //加载图片
        DocPicture picture = new DocPicture(doc);
        picture.loadImage(imageWatermark.getPath());

        //设置图片环绕方式
        picture.setTextWrappingStyle(TextWrappingStyle.Behind);

        picture.setHeightScale(20);
        picture.setWidthScale(15);

        for (int n = 0; n < doc.getSections().getCount(); n++) {
            Section section = doc.getSections().get(n);
            //获取section的页眉
            HeaderFooter header = section.getHeadersFooters().getHeader();
            Paragraph paragrapg;
            if (header.getParagraphs().getCount() > 0) {
                paragrapg = header.getParagraphs().get(0);

            } else {
                //添加段落到页眉
                paragrapg = header.addParagraph();
            }
            // 获取页面的高度和宽度
            // 获取页面的高度和宽度
            double height = section.getPageSetup().getPageSize().getHeight();
            double width = section.getPageSetup().getPageSize().getWidth();
            final int pageModeOfHorizontalInterval = imageWatermark.getPageModeOfHorizontalInterval() == null ? 50 : imageWatermark.getPageModeOfHorizontalInterval();
            final int pageModeOfVerticalInterval = imageWatermark.getPageModeOfVerticalInterval() == null ? (int) (picture.getHeight()*picture.getWidthScale()/100) : imageWatermark.getPageModeOfVerticalInterval();
            for (float posX = 0f; posX < width; posX = posX + picture.getWidth()*picture.getWidthScale()/100 + pageModeOfHorizontalInterval) {
                for (float posY = 0f; posY < height; posY = posY + pageModeOfVerticalInterval) {
                    picture = (DocPicture) picture.deepClone();
                    picture.setVerticalPosition(posX);
                    picture.setHorizontalPosition(posY);
                    paragrapg.getChildObjects().add(picture);
                }
            }
//            for (int p = 0; p < 3; p++) {
//
//                for (int q = 0; q < 2; q++) {
//                    //复制图片并设置多行多列位置
//                    picture = (DocPicture) picture.deepClone();
//                    picture.setVerticalPosition(1 + 200 * p);
//                    picture.setHorizontalPosition(5 + 210 * q);
//                    paragrapg.getChildObjects().add(picture);
//                }
//            }
        }
        //保存文档
        destPath = StringUtils.isNotEmpty(destPath) ? destPath : newFileName(srcPath);
        doc.saveToFile(destPath, FileFormat.Docx_2013);
        return destPath;
    }

    public static String imgWatermark(ImageWatermark imageWatermark, String srcPath, String destPath) {
        Document doc = new Document();
        doc.loadFromFile(srcPath);
        PictureWatermark picture = new PictureWatermark();
        picture.setPicture(imageWatermark.getPath());
        picture.setScaling(5);
        picture.isWashout(false);
        doc.setWatermark(picture);

        destPath = StringUtils.isNotEmpty(destPath) ? destPath : newFileName(destPath);
        doc.saveToFile(destPath, FileFormat.Docx_2013);
        return destPath;
    }

}
